/**@type {WebSocket} */
let ws = new WebSocket('ws://127.0.0.1:12139');
// let ws = new WebSocket('ws://175.27.232.13:12139');
ws.onopen = function () {
     console.log("onopen");
}
ws.onclose = function () {
     console.log("onclose");
}
ws.onerror = function (e) {
     console.log("onerror", e);
}

ws.onmessage = function (e) {
     console.log("onmessage", e);

    const msg = JSON.parse(e.data);
    const list = listenerMap[msg.name];
    if (list) {
        for (const callback of list) {
            callback(msg.success, msg.data);
        }
    }
}

function sendMsg(name, data) {
    ws.send(JSON.stringify({
        name,
        data
    }));
}

const listenerMap = {};
function onMessage(name, callback) {
    if (!listenerMap[name]) {
        listenerMap[name] = [];
    }

    listenerMap[name].push(callback);
}

function offMessage(name, callback) {
    if (!listenerMap[name]) {
         console.log("can not find the name");
        return;
    }

    const list = listenerMap[name];
    listenerMap[name] = list.filter(e => e !== callback);
}